package com.bwie.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.utils.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Dict;
import com.bwie.mapper.DictMapper;
import com.bwie.service.DictService;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.PostConstruct;

@Service
@Transactional
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostConstruct
    public void loadDictList(){
        System.out.println("项目启动时,加载字典列表到缓存中");
        List<Dict> dicts = dictMapper.selectList(null);
        for (Dict dict : dicts) {
            String key1 = "dict-"+dict.getDictType();
            String key2 = ""+dict.getDictId();
            redisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(dict));
        }
        System.out.println("加载字典列表成功");
    }

    @Override
    public R getDictList(Integer typeId) {
        String key1 = "dict-"+typeId;
        Boolean b = redisTemplate.hasKey(key1);
        if(b){
            System.out.println("从缓存中读取字典列表");
            List<Object> values = redisTemplate.opsForHash().values(key1);
            ArrayList<Dict> dicts = new ArrayList<>();
            for (Object value : values) {
                Dict dict = JSON.parseObject(value.toString(), Dict.class);
                dicts.add(dict);
            }
            return R.OK(dicts);
        }
        System.out.println("从数据库中读取字典列表");
        List<Dict> dicts = dictMapper.selectList(
                new QueryWrapper<Dict>().lambda().eq(Dict::getDictType, typeId)
        );
        for (Dict dict : dicts) {
            String key = "dict-"+dict.getDictType();
            String key3 = ""+dict.getDictId();
            redisTemplate.opsForHash().put(key,key3,JSON.toJSONString(dict));
        }
        return R.OK(dicts);
    }
}
